/*
 * Copyright (C) 2003-2009 eXo Platform SAS.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.reflext.api.introspection;

import org.reflext.api.MethodInfo;
import org.reflext.api.MethodSignature;
import org.reflext.api.ClassTypeInfo;

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

/**
 * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
 * @version $Revision$
 */
class MethodContainer implements Iterable<MethodInfo>  {

  /** . */
  private final Map<MethodSignature, MethodInfo> map = new HashMap<MethodSignature, MethodInfo>();

  /** . */
  private final ClassTypeInfo context;

  MethodContainer(ClassTypeInfo context) {
    this.context = context;
  }

  MethodContainer() {
    this.context = null;
  }

  public void addAll(Iterable<MethodInfo> methods) {
    for (MethodInfo method : methods) {
      add(method);
    }
  }

  public boolean add(MethodInfo method) {
    MethodSignature key;
    if (context != null) {
      key = method.getSignature(context);
    } else {
      key = method.getSignature();
    }

    //
    MethodInfo existing = map.get(key);

    //
    if (existing != null) {
      if (method.getReturnType().isSubType(existing.getReturnType())) {
        if (existing.getOwner().isAssignableFrom(method.getOwner())) {
          map.put(key, method);
          return true;
        }
      }
    } else {
      map.put(key, method);
      return true;
    }

    //
    return false;
  }

  public Set<MethodInfo> toCollection() {
    return new HashSet<MethodInfo>(map.values());
  }

  public Iterator<MethodInfo> iterator() {
    return map.values().iterator();
  }
}
